﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WQLAPI.Helper;

namespace TestXmodem_1K
{
    public partial class Form1 : Form
    {
        SerialPortHelper sport = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "文件|*.bin;*.fxt";
            fd.RestoreDirectory = true;
            fd.InitialDirectory = Environment.CurrentDirectory;
            DialogResult dr = fd.ShowDialog();
            if (dr == DialogResult.OK || dr == DialogResult.Yes)
            {
                textBox1.Text = fd.FileName;

            }
            else
            {
                MessageBox.Show("请选择配置文件");

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            sport = new SerialPortHelper("COM3", 57600);

            string BackValues = string.Empty;
            string BackFile = string.Empty;
            try
            {
                if (sport.Open())
                {
                    byte[] byteArray = Encoding.Default.GetBytes(textBox2.Text.ToString());
                    if (sport.SendData(byteArray))
                    {
                        System.Threading.Thread.Sleep(2000);
                        byte[] ThirdBytes = sport.ReadByte();
                        BackValues += Encoding.Default.GetString(ThirdBytes);
                        if (BackValues.Contains("C"))
                        {
                            //发送文件
                            //FileSend send = new FileSend();
                            sport.SendBytes(textBox1.Text.ToString());
                            for (int i = 0; i < 200; i++)
                            {
                                System.Threading.Thread.Sleep(10);
                                byte[] ThirdBytes2 = sport.ReadByte();
                                if (ThirdBytes2.Length > 0)
                                {
                                    Console.WriteLine(Encoding.Default.GetString(ThirdBytes2));
                                    BackFile += Encoding.Default.GetString(ThirdBytes2);
                                    break;
                                }

                            }
                        }
                    }
                    sport.Close();
                    textBox3.Text = BackValues + BackFile;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
    }
}
